<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
set_time_limit(0);
date_default_timezone_set("America/Chicago");
ini_set("memory_limit", "200M");

$expected = array(
		'cmd'
	,	'id'
	,	'data'
	,	'authority'
	,	'location'
	,	'database'
	,	'browseAuthority'
	, 'source'
	,	'limit'
	,	'start'
	,	'sort'
	,	'dir'
	,	'dwcaFile'
);

// Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? stripslashes(${"_$_SERVER[REQUEST_METHOD]"}[$formvar]) : NULL;

$allowedExt = array("zip", "gz", "tar", "gzip");

switch($cmd) {

	case 'getDbList':
		require_once('classes/class.database.php');
		$db = new database();
		$results = $db->getList();
		header('Content-type: application/json');
		if ($results) {
			print json_encode( array('success' => true, 'totalCount' => $db->getCount(), 'data' => $results));
		} else {
			print json_encode( array('success' => true, 'totalCount' => $db->getCount(), 'data' => array()));
		}
		break;

	case 'getDbById':
		require_once('classes/class.database.php');
		$db = new database();
		$results = $db->getById($id);
		header('Content-type: application/json');
		if ($results) {
			print json_encode( array('success' => true, 'totalCount' => $db->getCount(), 'data' => $results));
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 101, 'msg' => 'Database record not found.')) );
		}
		break;

	case 'addDatabase':
		require_once('classes/class.database.php');
		$db = new database();
		$values = json_decode($data, true);
		$results = $db->addDatabase( $values );
		header('Content-type: application/json');

		if ($results) {
			print json_encode( array('success' => true, 'data' => $results ) );
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 102, 'msg' => 'Database could not be added.')) );
		}
		break;

	case 'updateDatabase':
		require_once('classes/class.database.php');
		$db = new database();

		$results = $db->updateDatabase( json_decode($data, true) );
		header('Content-type: application/json');

		if ($results) {
			print json_encode( array('success' => true, 'data' => 'Database updated.') );
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 102, 'msg' => 'Database could not be added.')) );
		}
		break;

	case 'deleteDatabase':
		require_once('classes/class.database.php');
		$db = new database();
		$data = stripslashes(trim($data,'"'));
		$results = $db->deleteDatabase($data);
		header('Content-type: application/json');
		if ($results) {
			print json_encode( array('success' => true) );
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 101, 'msg' => 'Database record not found.')) );
		}
		break;

	case 'getAuthorityList':
		require_once('classes/class.authorities.php');
		$auth = new authorities();
		$results=$auth->getAuthorityList();
		header('Content-type: application/json');

		if ($results) {
			print json_encode( array('success' => true, 'totalCount' => $auth->getCount(), 'data' => $results));
		} else {
			print json_encode( array('success' => true, 'totalCount' => $auth->getCount(), 'data' => array()) );
		}
		break;

	case 'getAuthById':
		require_once('classes/class.authorities.php');
		$auth = new authorities();
		$results=$auth->getAuthById($id);
		header('COntent-type: application/json');
		if($results){
			print json_encode(array('success' => true, 'totalCount' => $auth->getCount(), 'data' => $results));
		} else {
			print json_encode(array('success' => false, 'error' => array('id' => 101,  'msg' => 'Record not found')));
		}
		break;

	case 'deleteAuthority':
		require_once('classes/class.authorities.php');
		$auth = new authorities();
		$data = stripslashes(trim($data,'"'));
		$results = $auth->deleteAuthority($data, $database);

		header('Content-type: application/json');
		if ($results) {
			print json_encode( array('success' => true, 'msg' => 'Authority deleted successfully') );
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 101, 'msg' => 'Authority not found.')) );
		}
		break;

	case 'addAuthority':
#		header('Content-type: application/json');
		$tmpFolder = sys_get_temp_dir() . "/";
		$fileId = uniqid();
		$sqlFile = $tmpFolder . $fileId . ".sql";

// $tExt = 'zip';

		if ($location != '') {
# url processing
			$tPathParts = pathinfo($location);
			$tExt = $tPathParts['extension'];
			if(in_array($tExt, $allowedExt)){
				$test = @file_put_contents($tmpFolder . $fileId . "." . $tExt, file_get_contents($location));
				if (!$test) {
					print json_encode( array('success' => false,'error' => array('id' => 106, 'msg' => 'The url to archive was not a valid link at this time.')));
					break;
				}
			} else {
				print json_encode( array('success' => false,'error' => array('id' => 106,'msg' => 'DarwinCore Archive must be tar/gzip/zip"')));
				break;
			}
		} elseif (isset($_FILES['dwcaFile']['tmp_name'])) {
# uploaded dwca processing
			if ($_FILES["dwcaFile"]["error"] > 0){
				print json_encode( array('success' => false, 'error' => array('id' => 107, 'msg' => 'Error while uploading file.')) );
				break;
			} else {
				$tPathParts = pathinfo($_FILES["dwcaFile"]["name"]);
				$tExt = $tPathParts['extension'];
				if(in_array($tExt, $allowedExt)){
					if (! move_uploaded_file($_FILES["dwcaFile"]["tmp_name"], $tmpFolder . $fileId . "." . $tExt) ) {
						print json_encode( array('success' => false, 'error' => array('id' => 110,'msg' => 'DarwinCore Archive could not be moved to process after uploading."')));
						break;
					}
				} else {
					print json_encode( array('success' => false,'error' => array('id' => 106,'msg' => 'DarwinCore Archive must be tar/gzip/zip"')));
					break;
				}
			}
		} else {
			print json_encode( array('success' => false, 'error' => array('id' => 103, 'msg' => 'Authority file not provided.')) );
			break;
		}

// copy('/var/www/html/taxamatch/if_dataset.zip',$tmpFolder . $fileId . "." . $tExt);
// echo '<pre>';

		include_once('classes/class.darwincorearchivereader.php');
		include_once('classes/class.install_authority.php');
		require_once('classes/class.authorities.php');
		$auth = new authorities();
		$file = $tmpFolder . $fileId;
		$dwca = new DarwinCoreArchiveReader($tmpFolder . $fileId . "." . $tExt);
// exit;
// print_r($dwca->core);
		$iauth = new install_authority();
		$authority = strtolower(str_replace(" ", "_", $authority));
		$iauth->setName($authority);
		$handle = fopen($sqlFile, "w");
		$query = $iauth->createTables();
		fwrite($handle, $query);

		$genAr = array();
		include_once('../../../api/classes/class.normalize.php');
		include_once('../../../api/classes/class.taxamatch_splitter.php');
#print "<pre>";		
		while($row = $dwca->getRow()) {
#print_r($row);
			if ($ij++ == 2000000) {
				print "Ouch I hit 2mil records.";
				exit();
			}
			if ($row) {
				switch($row["taxonrank"]) {
					case 'order': 
					case 'superorder':
					case 'subclass':
					case 'class':
					case 'kingdom':
					case 'subfamily':
					case 'tribe':
					case 'subtribe':
					case 'subgenus':
					case 'section':
					case 'subsection':
					case 'series':
					case 'variety':
					case 'subspecies':
						break;

					case 'family':
						break;

					case 'genus':
					case 'gen.':
						$genus_parts = explode(" ", $row["scientificname"]);
						$genus = array_shift($genus_parts);
						$tmp_auth = trim(implode(" ", $genus_parts));
						if ($tmp_auth != '' && $row["scientificnameauthorship"] == '') {
							$row["scientificnameauthorship"] = $tmp_auth;
						}
						
						if (isset($genAr[$genus])) {
							$genus_id = $genAr[$genus];
						} else {
							$genIndex++;
							$genAr[$genus] = $genIndex;
							$genus_id = $genIndex;
							$query = $iauth->getGenus($genus_id, $genus, $row["scientificnameauthorship"]);
#							print '<br>' . $query . "<br>";
							fwrite($handle, $query);
						}
						break;
						
					case 'species':
					case 'spec.':
						$norm = new Normalize();
						$sp = new Splitter($norm, $row["scientificname"]);
						$genus = ucfirst(strtolower($sp->get('genus')));
						$species = strtolower($sp->get('species'));

						if ($sp->author != '' && $row["scientificnameauthorship"] == '') {
							$row["scientificnameauthorship"] = $sp->author;
						}

						if (isset($genAr[$genus])) {
							$genus_id = $genAr[$genus];
						} else {
							$genIndex++;
							$genAr[$genus] = $genIndex;
							$genus_id = $genIndex;
							$query = $iauth->getGenus($genus_id, $genus, $row["scientificnameauthorship"]);
							fwrite($handle, $query);							
						}

						if ($species != '') {
							$species_id++;
							$query = $iauth->getSpecies($species_id, $species, $genus_id, $genus, $row["scientificnameauthorship"]);
#							print '<br>' . $query . "<br>";
							fwrite($handle, $query);
						}

						break;

					default:
// print "<br> Taxon Rank ::" . $row["taxonrank"] . "<br>";
						$norm = new Normalize();
						$sp = new Splitter($norm, $row["scientificname"]);
						$genus = ucfirst(strtolower($sp->get('genus')));
						$species = strtolower($sp->get('species'));

						if ($sp->author != '' && $row["scientificnameauthorship"] == '') {
							$row["scientificnameauthorship"] = $sp->author;
						}

						if (isset($genAr[$genus])) {
							$genus_id = $genAr[$genus];
						} else {
							$genIndex++;
							$genAr[$genus] = $genIndex;
							$genus_id = $genIndex;
							$query = $iauth->getGenus($genus_id, $genus, $row["scientificnameauthorship"]);
							fwrite($handle, $query);
						}

						if ($species != '') {
							$species_id++;
							$query = $iauth->getSpecies($species_id, $species, $genus_id, $genus, $row["scientificnameauthorship"]);
							fwrite($handle, $query);
						}
						break;
				}
			}
		}
		fclose($handle);
#exit();		
		include_once("../../../api/database.php");
		$command = sprintf(" mysql -h %s -u %s -p%s %s < %s "
			, $config[$database]["server"]
			, $config[$database]["userName"]
			, $config[$database]["pass"]
			, $config[$database]["name"]
			, $sqlFile
		);
		exec($command);
		$auth->addAuthority($authority, $config[$database]);
		unlink($sqlFile);
		unlink($tmpFolder . $fileId . "." . $tExt);
		print json_encode( array('success' => true, 'msg' => 'Authority added.') );
		break;

	case 'getArchives':
		$res = json_decode(@file_get_contents("http://ecat-dev.gbif.org/ws-registry/resource?type=DWC-ARCHIVE"), true);
		if(is_array($res) && count($res)) {
		foreach($res as $key => &$rec) {
			if ($rec["services"]) {
			foreach($rec["services"] as $service) {
				$parts = pathinfo($service["url"]);
				if ( ($service["type"] == "DWC-ARCHIVE" || $service["type"] == "DWC-ARCHIVE-CHECKLIST" || $service["type"] == "DWC-ARCHIVE-OCCURRENCE") && trim($service["url"]) != '' && strtolower($parts['extension']) != 'csv') {
					$rec["url"] = $service["url"];
					break;
				}
			}
			}
			unset($rec["services"]);
			if ($rec["url"] == "") {
#				print "<br> $key";
#				print_r($res[$key]);
				unset($res[$key]);
			}
		}
		}
		$res = @array_values($res);
		header('Content-type: application/json');
		print json_encode($res);
		break;

	case 'browseAuthority':
		require_once('classes/class.authorities.php');
		header('Content-type: application/json');
		$ob = new authorities();
		$data["start"] = $start;
		$data["limit"] = $limit;
		$data["sort"] = $sort;
		$data["dir"] = $dir;
		$result = $ob->getValue($source, $database, $data);
		if($result) {
			print json_encode( array( 'success' => true , 'totalCount' => $result["totalCount"], 'data' => $result["data"]));
		} else {
			print json_encode(array("success" => false, "error" =>"record not found"));
		}
		break;

	case 'exportTM':
		include_once("../../../api/database.php");
		foreach($config as $key => $value){
			if($value['name'] == $database){
				$s = $config[$key];
				break;
			}
		}
		$fileName = sprintf('../tmp/%s.sql.gz', $source);
		$command = sprintf("mysqldump -u %s -p%s %s | gzip -9 > %s "
			, $s["userName"]
			, $s["pass"]
			, $s["name"]
			, $fileName
		);
		exec($command);

		header("Content-type: application/zip");
		header("Content-Disposition: attachment; filename=$fileName");
		header("Pragma: no-cache");
		header("Expires: 0");
		readfile("$fileName");
		exit();
		break;

}
?>